{% extends "base.html" %}

{% block title %}数据管理 - XCQuant{% endblock %}

{% block breadcrumb %}
<nav aria-label="breadcrumb">
    <ol class="breadcrumb">
        <li class="breadcrumb-item"><a href="{{ url_for('index') }}">首页</a></li>
        <li class="breadcrumb-item active">数据管理</li>
    </ol>
</nav>
{% endblock %}

{% block content %}
<!-- 页面标题 -->
<div class="d-flex justify-content-between align-items-center mb-4">
    <h1 class="h3 mb-0 text-gray-800">
        <i class="fas fa-database me-2"></i>数据管理
    </h1>
</div>

<!-- 数据下载区域 -->
<div class="row">
    <div class="col-lg-8">
        <div class="card shadow mb-4">
            <div class="card-header py-3">
                <h6 class="m-0 font-weight-bold text-primary">
                    <i class="fas fa-download me-2"></i>数据下载
                </h6>
            </div>
            <div class="card-body">
                <form id="downloadForm">
                    <div class="row">
                        <div class="col-md-6">
                            <div class="form-group mb-3">
                                <label for="exchange">交易所</label>
                                <select class="form-control" id="exchange" name="exchange" required>
                                    <option value="">请选择交易所</option>
                                    <option value="okx">OKX</option>
                                    <option value="binance">Binance</option>
                                </select>
                            </div>
                        </div>
                        <div class="col-md-6">
                            <div class="form-group mb-3">
                                <label for="trade_type">交易类型</label>
                                <select class="form-control" id="trade_type" name="trade_type" required>
                                    <option value="">请选择交易类型</option>
                                    <option value="spot">现货</option>
                                    <option value="futures">合约</option>
                                </select>
                            </div>
                        </div>
                    </div>
                    
                    <div class="row">
                        <div class="col-md-6">
                            <div class="form-group mb-3">
                                <label for="symbol">交易对</label>
                                <input type="text" class="form-control" id="symbol" name="symbol" 
                                       placeholder="例如: BTC-USDT" required>
                                <small class="form-text text-muted">格式: BASE-QUOTE (如 BTC-USDT)</small>
                            </div>
                        </div>
                        <div class="col-md-6">
                            <div class="form-group mb-3">
                                <label for="interval">时间间隔</label>
                                <select class="form-control" id="interval" name="interval" required>
                                    <option value="">请选择时间间隔</option>
                                    <option value="1m">1分钟</option>
                                    <option value="5m">5分钟</option>
                                    <option value="15m">15分钟</option>
                                    <option value="1h">1小时</option>
                                    <option value="4h">4小时</option>
                                    <option value="1d">1天</option>
                                </select>
                            </div>
                        </div>
                    </div>
                    
                    <div class="row">
                        <div class="col-md-6">
                            <div class="form-group mb-3">
                                <label for="start_date">开始日期</label>
                                <input type="date" class="form-control" id="start_date" name="start_date" required>
                            </div>
                        </div>
                        <div class="col-md-6">
                            <div class="form-group mb-3">
                                <label for="end_date">结束日期</label>
                                <input type="date" class="form-control" id="end_date" name="end_date" required>
                            </div>
                        </div>
                    </div>
                    
                    <div class="form-group mb-3">
                        <button type="submit" class="btn btn-primary">
                            <i class="fas fa-download me-2"></i>开始下载
                        </button>
                        <button type="button" class="btn btn-secondary ms-2" onclick="resetForm()">
                            <i class="fas fa-undo me-2"></i>重置
                        </button>
                    </div>
                </form>
                
                <!-- 下载进度 -->
                <div id="downloadProgress" class="mt-4" style="display: none;">
                    <div class="progress mb-2">
                        <div class="progress-bar" role="progressbar" style="width: 0%" 
                             aria-valuenow="0" aria-valuemin="0" aria-valuemax="100"></div>
                    </div>
                    <div class="text-center">
                        <small class="text-muted" id="progressText">准备下载...</small>
                    </div>
                </div>
                
                <!-- 下载结果 -->
                <div id="downloadResult" class="mt-4" style="display: none;">
                    <div class="alert" role="alert">
                        <div id="resultMessage"></div>
                    </div>
                </div>
            </div>
        </div>
    </div>
    
    <!-- 数据统计 -->
    <div class="col-lg-4">
        <div class="card shadow mb-4">
            <div class="card-header py-3">
                <h6 class="m-0 font-weight-bold text-primary">
                    <i class="fas fa-chart-bar me-2"></i>数据统计
                </h6>
            </div>
            <div class="card-body">
                <div class="mb-3">
                    <div class="small text-gray-500">本地数据文件</div>
                    <div class="h5 mb-0 font-weight-bold text-gray-800" id="localFileCount">--</div>
                </div>
                <div class="mb-3">
                    <div class="small text-gray-500">数据总大小</div>
                    <div class="h5 mb-0 font-weight-bold text-gray-800" id="totalDataSize">--</div>
                </div>
                <div class="mb-3">
                    <div class="small text-gray-500">最新更新</div>
                    <div class="h5 mb-0 font-weight-bold text-gray-800" id="lastUpdate">--</div>
                </div>
                <button class="btn btn-outline-primary btn-sm w-100" onclick="refreshDataStats()">
                    <i class="fas fa-sync-alt me-1"></i>刷新统计
                </button>
            </div>
        </div>
        
        <!-- 快速下载预设 -->
        <div class="card shadow">
            <div class="card-header py-3">
                <h6 class="m-0 font-weight-bold text-primary">
                    <i class="fas fa-bolt me-2"></i>快速下载
                </h6>
            </div>
            <div class="card-body">
                <div class="d-grid gap-2">
                    <button class="btn btn-outline-success btn-sm" onclick="quickDownload('BTC-USDT', 'spot', '1h', 30)">
                        BTC现货 1小时 (30天)
                    </button>
                    <button class="btn btn-outline-success btn-sm" onclick="quickDownload('ETH-USDT', 'spot', '1h', 30)">
                        ETH现货 1小时 (30天)
                    </button>
                    <button class="btn btn-outline-warning btn-sm" onclick="quickDownload('BTC-USDT', 'futures', '1h', 30)">
                        BTC合约 1小时 (30天)
                    </button>
                    <button class="btn btn-outline-warning btn-sm" onclick="quickDownload('ETH-USDT', 'futures', '1h', 30)">
                        ETH合约 1小时 (30天)
                    </button>
                </div>
            </div>
        </div>
    </div>
</div>

<!-- 数据文件列表 -->
<div class="card shadow mt-4">
    <div class="card-header py-3">
        <h6 class="m-0 font-weight-bold text-primary">
            <i class="fas fa-list me-2"></i>本地数据文件
        </h6>
    </div>
    <div class="card-body">
        <div class="table-responsive">
            <table class="table table-bordered" id="dataFilesTable">
                <thead>
                    <tr>
                        <th>文件名</th>
                        <th>交易所</th>
                        <th>交易对</th>
                        <th>类型</th>
                        <th>时间间隔</th>
                        <th>大小</th>
                        <th>修改时间</th>
                        <th>操作</th>
                    </tr>
                </thead>
                <tbody id="dataFilesBody">
                    <tr>
                        <td colspan="8" class="text-center text-muted">
                            <i class="fas fa-spinner fa-spin me-2"></i>加载中...
                        </td>
                    </tr>
                </tbody>
            </table>
        </div>
    </div>
</div>
{% endblock %}

{% block scripts %}
<script>
$(document).ready(function() {
    // 初始化页面
    initializePage();
    
    // 设置默认日期
    setDefaultDates();
    
    // 加载数据文件列表
    loadDataFiles();
    
    // 加载数据统计
    refreshDataStats();
});

// 初始化页面
function initializePage() {
    // 表单提交处理
    $('#downloadForm').on('submit', function(e) {
        e.preventDefault();
        startDownload();
    });
}

// 设置默认日期
function setDefaultDates() {
    const today = new Date();
    const thirtyDaysAgo = new Date(today.getTime() - 30 * 24 * 60 * 60 * 1000);
    
    $('#end_date').val(today.toISOString().split('T')[0]);
    $('#start_date').val(thirtyDaysAgo.toISOString().split('T')[0]);
}

// 开始下载
function startDownload() {
    const formData = {
        exchange: $('#exchange').val(),
        trade_type: $('#trade_type').val(),
        symbol: $('#symbol').val(),
        interval: $('#interval').val(),
        start_date: $('#start_date').val(),
        end_date: $('#end_date').val()
    };
    
    // 显示进度条
    $('#downloadProgress').show();
    $('#downloadResult').hide();
    
    // 发送下载请求
    $.ajax({
        url: '/api/data/download',
        method: 'POST',
        contentType: 'application/json',
        data: JSON.stringify(formData),
        success: function(response) {
            if (response.success) {
                showDownloadResult('success', '数据下载成功！');
                loadDataFiles(); // 刷新文件列表
                refreshDataStats(); // 刷新统计
            } else {
                showDownloadResult('danger', '下载失败: ' + response.message);
            }
        },
        error: function(xhr, status, error) {
            showDownloadResult('danger', '下载失败: ' + error);
        },
        complete: function() {
            $('#downloadProgress').hide();
        }
    });
}

// 显示下载结果
function showDownloadResult(type, message) {
    $('#downloadResult').show();
    $('#downloadResult .alert').removeClass().addClass('alert alert-' + type);
    $('#resultMessage').text(message);
}

// 快速下载
function quickDownload(symbol, tradeType, interval, days) {
    const endDate = new Date();
    const startDate = new Date(endDate.getTime() - days * 24 * 60 * 60 * 1000);
    
    $('#symbol').val(symbol);
    $('#trade_type').val(tradeType);
    $('#interval').val(interval);
    $('#start_date').val(startDate.toISOString().split('T')[0]);
    $('#end_date').val(endDate.toISOString().split('T')[0]);
    $('#exchange').val('okx'); // 默认使用OKX
    
    startDownload();
}

// 重置表单
function resetForm() {
    $('#downloadForm')[0].reset();
    setDefaultDates();
    $('#downloadProgress').hide();
    $('#downloadResult').hide();
}

// 加载数据文件列表
function loadDataFiles() {
    $.ajax({
        url: '/api/data/files',
        method: 'GET',
        success: function(response) {
            if (response.success) {
                updateDataFilesTable(response.data);
            }
        },
        error: function() {
            $('#dataFilesBody').html('<tr><td colspan="8" class="text-center text-danger">加载失败</td></tr>');
        }
    });
}

// 更新数据文件表格
function updateDataFilesTable(files) {
    const tbody = $('#dataFilesBody');
    tbody.empty();
    
    if (files.length === 0) {
        tbody.html('<tr><td colspan="8" class="text-center text-muted">暂无数据文件</td></tr>');
        return;
    }
    
    files.forEach(function(file) {
        const row = `
            <tr>
                <td>${file.filename}</td>
                <td>${file.exchange || '--'}</td>
                <td>${file.symbol || '--'}</td>
                <td>${file.trade_type || '--'}</td>
                <td>${file.interval || '--'}</td>
                <td>${file.size}</td>
                <td>${file.modified_time}</td>
                <td>
                    <button class="btn btn-sm btn-outline-primary" onclick="viewFile('${file.filename}')">
                        <i class="fas fa-eye"></i>
                    </button>
                    <button class="btn btn-sm btn-outline-danger" onclick="deleteFile('${file.filename}')">
                        <i class="fas fa-trash"></i>
                    </button>
                </td>
            </tr>
        `;
        tbody.append(row);
    });
}

// 刷新数据统计
function refreshDataStats() {
    $.ajax({
        url: '/api/data/stats',
        method: 'GET',
        success: function(response) {
            if (response.success) {
                $('#localFileCount').text(response.data.file_count);
                $('#totalDataSize').text(response.data.total_size);
                $('#lastUpdate').text(response.data.last_update);
            }
        }
    });
}

// 查看文件
function viewFile(filename) {
    window.open('/api/data/view/' + filename, '_blank');
}

// 删除文件
function deleteFile(filename) {
    if (confirm('确定要删除文件 ' + filename + ' 吗？')) {
        $.ajax({
            url: '/api/data/delete/' + filename,
            method: 'DELETE',
            success: function(response) {
                if (response.success) {
                    loadDataFiles();
                    refreshDataStats();
                    alert('文件删除成功');
                } else {
                    alert('删除失败: ' + response.message);
                }
            },
            error: function() {
                alert('删除失败');
            }
        });
    }
}
</script>
{% endblock %}